// pages/commitOrder/commitOrder.js
const app = getApp();
import httpsUtils from '../../utils/https.js';
import calcUtils from '../../utils/calcUtil.js';
import myUtils from '../../utils/util.js';

var fareInfo = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hasAddress: true,
    address: '',
    seleFare: true,
    carList: '',//购物车数据
    goodsMoney: 0.00,//商品价格
    goodsCount: 0,//商品数量
    freightMoney: 0.00,//运费
    totalMoney: 0.00,//合计
    freightType: 1,//默认1表示包邮，2表示快递，3表示货到付运费
    realFreightMoney: 0.00,//实际的运费
    remark:'',//备注
  },
  /**
   * 跳转地址
   */
  gotoAddress:function(){
    var pages = getCurrentPages();
    if (pages.length >= 2) {
      var info = pages[pages.length - 2].route;
      if (info == 'pages/address/address') {
        wx.navigateBack({
          delta: 2
        })
      } else {
        wx.navigateTo({
          url: "/pages/address/address",
        })
      }
    } else {
      wx.navigateTo({
        url: "/pages/address/address",
      })
    }
  },
  /**
   * 获取默认地址
   */
  getDefaultAddress: function () {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/address/selectDefault',
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        that.setData({
          address: json.data,
          hasAddress: true,
        })
        that.getFreightMoney(json.data.id);
      }else{
        that.setData({
          hasAddress: false,
        })
      }
    })
  },
  /**
   * 获取非默认地址
   */
  getAddressById: function (e) {
    var that = this;
    httpsUtils.getData({
      _url: app.globalData._url + '/address/selectOne?id=' + e,
      data: {},
    }, function (json) {
      if (json.data && json.success) {
        that.setData({
          address: json.data,
          hasAddress: true,
        })
        that.getFreightMoney(e);
      }
    })
  },
  /**
   * 计算运费
   */
  getFreightMoney: function (id) {
    var that = this;
    var carList = that.data.carList;

    var param = [];
    for (let shop of carList) {
      var weight = 0;
      for (let goods of shop.goodsList) {
        weight = calcUtils.add(calcUtils.mul(goods.goodsCar.goodsNumber, goods.weight), weight);
      }
      param.push({ shopId: shop.id, addressId: id, weight: weight })
    }

    //有商品重量，大于0表示有运费，小于等于0表示包邮
    if (weight > 0) {
      var carList = that.data.carList;
      httpsUtils.postData({
        _url: app.globalData._url + '/expressPrice/selectShopExpressPrice',
        data: { param: param },
      }, function (json) {
        if (json.data && json.success) {
          var freightType = that.data.freightType;
          var goodsMoney = that.data.goodsMoney;
          var totalMoney = that.data.totalMoney;
          var realFreightMoney = 0.00;
          var carList = that.data.carList;
          var freightMoney = 0.00;
          freightMoney = json.data.allExpressPrice;

          //快递
          if (that.data.freightType == 1) {
            totalMoney = calcUtils.add(goodsMoney, freightMoney).toFixed(2);
            realFreightMoney = freightMoney;
          } else {
            realFreightMoney = 0.00;
          }

          //设置店铺运费
          for (let shop of carList) {
            for (let express of json.data.goodsExpressPrice) {
              if (shop.id == express.shopId){
                shop.expressPrice = express.expressPrice;
              }
            }
          }

          that.setData({
            carList: carList,
            freightMoney: freightMoney.toFixed(2),
            totalMoney: totalMoney,
            realFreightMoney: realFreightMoney.toFixed(2),
            freightType:2
          })
        }
      })
    } else {
      var carList = that.data.carList;
      for (let shop of carList) {
        shop.expressPrice = 0.00;
      }
      that.setData({
        carList: carList,
        freightType: 1,
      })
    }


  },
  /**
   * 获取商品信息
   */
  getGoodsInfo: function () {
    var that = this;
    // 计算商品总价
    var totalGoodsMoney = 0.00;
    var goodsCount = 0;
    var totalMoney = 0.00;
    var realFreightMoney = 0.00;
    realFreightMoney = that.data.realFreightMoney;
    var carList = wx.getStorageSync("payCarList");

    for (let shop of carList) {
      var shopGoodsMoney = 0.00;
      for (let goods of shop.goodsList) {
        var goodsMoney = calcUtils.mul(goods.goodsCar.goodsNumber, goods.goodsCar.packRate).toFixed(2);
        totalGoodsMoney = calcUtils.add(goodsMoney, totalGoodsMoney).toFixed(2);
        shopGoodsMoney = calcUtils.add(goodsMoney, shopGoodsMoney).toFixed(2);
      }
      shop.shopGoodsMoney = shopGoodsMoney;
      goodsCount += shop.goodsList.length;
    }
    totalMoney = calcUtils.add(totalGoodsMoney, realFreightMoney).toFixed(2);

    //缓存中获取购物车
    that.setData({
      carList: carList,
      goodsMoney: totalGoodsMoney,
      goodsCount: goodsCount,
      realFreightMoney: realFreightMoney,
      totalMoney: totalMoney
    })
  },
  /**
   * 选择运费方式
   */
  chooseFreightType: function (e) {
    var that = this;
    var freightType = parseInt(e.currentTarget.dataset.type);

    var freightMoney = that.data.freightMoney;
    var goodsMoney = that.data.goodsMoney;
    var totalMoney = 0.00;
    var realFreightMoney = 0.00;

    if (freightType == 2) {
      totalMoney = calcUtils.add(goodsMoney, freightMoney);
      realFreightMoney = freightMoney;
    }
    if (freightType == 3) {
      totalMoney = goodsMoney;
    }

    that.setData({
      totalMoney: totalMoney,
      realFreightMoney: realFreightMoney.toFixed(2),
      freightType: freightType
    })

    that.closeFare();
  },

  /**
   * 确认订单
   */
  commitOrder: function () {
    var that = this;
    var carList = that.data.carList;
    var address = that.data.address;
    if (myUtils.isBlank(address)){
      wx.showModal({
        title: '提示',
        content: '请选择地址',
        showCancel:false,
        success:{
          
        }
      })
      return false;
    }
    wx.showLoading({
      title: '提交中...',
      mask: true,
    })
    var param = [];
    for (let shop of carList) {
      var weight = 0;
      var goodsId = [];
      var goodsCount = 0;
      var freightMoney = shop.expressPrice;//当前店铺运费
      var orderMoney = shop.shopGoodsMoney;//当前店铺商品金额
      var payMoney = calcUtils.add(freightMoney, orderMoney).toFixed(2);//当前店铺支付金额

      for (let goods of shop.goodsList) {
        goodsId.push(goods.id);
        weight = calcUtils.add(calcUtils.mul(goods.goodsCar.goodsNumber, goods.weight), weight);
        goodsCount += goods.goodsCar.goodsNumber;
      }

      param.push({
        shopId: shop.id,
        goodsId: myUtils.concatStr(goodsId, ","),
        payType: 0,//支付类型：默认1表示余额支付，2表示支付宝支付，3表示微信支付，4表示银联支付
        addressId: that.data.address.id,
        orderMoney: orderMoney,//商品金额
        payMoney: payMoney,//支付金额，商品+运费-金币-优惠券
        freightMoney: freightMoney,//运费
        goldMoney: 0.00,//金币金额
        goldNum: 0,//金币数
        saveMoney: 0.00,//优惠券
        userCouponId: 0,//优惠券id
        goodsNumber: goodsCount,
        giveType: that.data.freightType,//配送类型，默认1表示包邮，2表示快递，3表示物流到付
        remark: that.data.remark,
        orderType: 1,//默认1表示正常订单，2表示代客订单,3表示z订单
      })
    }

    httpsUtils.postData({
      _url: app.globalData._url + '/order/addValet2',
      data: { 'myOrder': JSON.stringify(param)},
    }, function (json) {
      if (json.data && json.success) {
        var payOrders = [];
        for(let obj of json.data){
          payOrders.push({ orderId: obj.id, orderMoney: obj.orderMoney, payMoney: obj.payMoney, freightMoney: obj.freightMoney, goodsNumber: obj.goodsNumber})
        }
        wx.setStorageSync('payOrders', payOrders);
        wx.redirectTo({
          url: '../pay/pay',
        })
      }else{
        wx.showToast({
          title: '提交失败',
          icon:'none'
        })
      }
      wx.hideLoading();
    })
  },

  /**
   * 获取备注
   */
  getRemark:function(e){
    var remark = e.detail.value;
    this.setData({
      remark: remark
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    var that = this;

    //获取商品
    that.getGoodsInfo();

    var addressId = wx.getStorageSync("addressId");
    if (myUtils.isBlank(addressId)) {
      //获取默认地址
      that.getDefaultAddress();
    } else {
      //获取非默认地址
      that.getAddressById(addressId);
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  addAddress: function () {
    wx.navigateTo({
      url: '../addAddress/addAddress',
    })
  },
  /*点击选择配送方式*/
  radioChange: function (e) {
    fareInfo = e.detail.value
  },
  fareSelect: function () {
    var that = this;
    that.setData({
      seleFare: false,
    })
  },
  /*关闭配送方式*/
  closeFare: function () {
    var that = this;
    that.setData({
      seleFare: true,
    })
  },

})